package com.zis.platform.common.authentication;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;
import org.apache.shiro.web.util.WebUtils;

import com.zis.exception.SysInfoCacheNullException;
import com.zis.exception.UserDisableException;
import com.zis.platform.common.util.CacheCoreUtil;
import com.zis.platform.core.entity.SysEntity;
import com.zis.util.URLHelper;

/**
 * 
 * <b>说明：</b>用户请求拦截器<br>
 * 用户访问连接过程对权限进行校验:如果会话超时则自动跳转到登录页面
 * 
 * @ClassName: CoreUserFilter
 * @author zhaohaitao(2543)
 * @date 2015-7-10 上午10:05:58
 * 
 */
public class CoreUserFilter extends UserFilter
{
    
    private Logger log = Logger.getLogger(CoreUserFilter.class);
    
    /**
     * 未登录重定向到登陆页
     */
    protected void redirectToLogin(ServletRequest req, ServletResponse resp)
        throws IOException
    {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        SysEntity sysInfo = CacheCoreUtil.getSysInfo(request);
        String loginUrl;
        if (sysInfo != null)
        {
            loginUrl = sysInfo.getLoginUrl();
            if (StringUtils.isEmpty(loginUrl))
            {
                String sysContentPath = URLHelper.getSysContentPath(request);
                loginUrl = sysContentPath + "/login.do";
            }
            WebUtils.issueRedirect(request, response, loginUrl);
        }
        else
        {
            try
            {
                throw new SysInfoCacheNullException();
            }
            catch (SysInfoCacheNullException e)
            {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
        throws Exception
    {
        Subject subject = SecurityUtils.getSubject();
        UserToken token = (UserToken)subject.getPrincipal();
        if (token == null || token.getUser().isEnable())
        {
            return super.onPreHandle(request, response, mappedValue);
        }
        else
        {
            // TODO 后期完善用户被禁用之后的处理
            throw new UserDisableException();
        }
    }
}
